package guava;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;

import java.util.*;

/**
 * 不可变集合，guava提供了很多Immutable集合，比如ImmutableList/ImmutableSet/ImmutableSortedSet/ImmutableMap/......
 *
 * @author Daniel
 */
public class ImmutableTest {

    public static void main(String[] args) {
        unmodifiableCollectionTest();

        immutableMapTest();

        multimapTest();

    }

    private static void multimapTest() {
        /*
            Multimap的实现类有：ArrayListMultimap/HashMultimap/LinkedHashMultimap/TreeMultimap/ImmutableMultimap/......
         */
        Multimap<String, String> multimap = ArrayListMultimap.create();

        multimap.put("tom", "man");
        multimap.put("tom", "woman");
        multimap.put("jack", "man");

        Collection<String> tom = multimap.get("tom");
        System.out.println("tom = " + tom);

    }

    private static void immutableMapTest() {

        Map<String, String> immutableMap = ImmutableMap.of("name", "tom", "sex", "man");

        // 抛出 UnsupportedOperationException
        immutableMap.put("wife", "no...");

    }

    public static void unmodifiableCollectionTest() {

        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");

        // 这种视图不够安全，不是真正意义上的快照
        // Collection<String> readOnlyList = Collections.unmodifiableCollection(list);
        Collection<String> readOnlyList = Collections.unmodifiableCollection(new ArrayList<>(list));

        // readOnlyList.add("c"); // 抛出 UnsupportedOperationException

        list.add("c");

        // 此时readOnlyList的元素数量变成了3个
        int size = readOnlyList.size();
        System.out.println("size = " + size);

    }

}
